<?php

namespace App\Http\Controllers\Admin\Question;

use App\Http\Controllers\Admin\BaseController;
use App\Http\Requests\Admin\Question\Question\CreateRequest;
use App\Http\Requests\Admin\Question\Question\UpdateRequest;
use App\Models\Question;
use App\Repositories\Admin\Question\QuestionRepository;
use Illuminate\Http\Request;

class QuestionController extends BaseController
{
    //
    public function __construct()
    {
        $this->repo = new QuestionRepository();
    }

    /**
     * 列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function fetchList(Request $request)
    {
        $where = [];
        $pid = $request->get('pid', 0);
        $where['pid'] = (int)$pid;
        $page = $this->repo->pagination($where, $request->only('tag'));
        $data = $page->toArray();
        $data['map_type'] = Question::$mapType;
        return $this->success($data);
    }

    /**
     * 获取信息
     * @param Question $question
     * @return \Illuminate\Http\JsonResponse
     */
    public function fetchInfo(Question $question){
        $tags = $question->tags->pluck('name');
        $question->correct_rate = $question->answer_num?round($question->correct_num/$question->answer_num*100,2):0;
        return $this->success($question);
    }
    /**
     * 创建题目
     * @param CreateRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function create(CreateRequest $request)
    {
        try {
            $question = $this->repo->create($request->all(), $request->get('tag_id', []));
            return $question ? $this->success($question, '添加成功') : $this->error('添加失败');

        } catch (\Exception $e) {
            return $this->error($e->getMessage(), [], 422);
        }
    }

    /**
     * 更新题目
     * @param UpdateRequest $request
     * @param Question $question
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(UpdateRequest $request, Question $question)
    {
        try {
            $question = $this->repo->patch($question, $request->all(), $request->get('tag_id', []));
            return $question ? $this->success($question, '更新成功') : $this->error('更新失败');
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), [], 422);
        }
    }

    /**
     * 修改状态
     * @param Question $question
     * @return \Illuminate\Http\JsonResponse
     */
    public function setStatus(Question $question)
    {
        return $this->repo->update($question, ['status' => !$question->status]) ?
            $this->success([], '更新成功') : $this->error('更新失败');
    }

    /**
     * 删除
     * @param Question $question
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delete(Question $question)
    {
        return $question->delete() ? $this->success([], '删除成功') : $this->error('删除失败');
    }
}
